package xna.android;

import xna.android.Telas.*;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Game1 extends SurfaceView implements
SurfaceHolder.Callback {

	private MainThread thread;

	enum Tela {INTRO, JOGO, CREDITS, };

	private Tela atual = Tela.INTRO;
	private Credits credits;
	private Intro intro;
	private Jogo jogo;
		
	public Game1(Context Content) {
		super(Content);

		getHolder().addCallback(this);
		
		thread = new MainThread(getHolder(), this);
		
		setFocusable(true);
	
		credits = new Credits(Content);
		intro = new Intro(Content);
		jogo = new Jogo(Content);
		thread = new MainThread(getHolder(), this);
	}

	public void surfaceCreated(SurfaceHolder holder)
	{
		thread.setRunning(true);
		thread.start();
	}


	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
	{
			
	}

	public void surfaceDestroyed(SurfaceHolder holder)
	{
		boolean retry = true;
		
		while (retry)
		{
			try
			{
				thread.join();
				retry = false;
			}
			catch (InterruptedException e)
			{  }
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) 
	{
		switch(atual)
		{
			case CREDITS :
				credits.onTouchEvent(event);
				if (credits.isTouched())
					atual = Tela.INTRO;
				break;
			case INTRO:
				intro.onTouchEvent(event);
				if (intro.getExit().isTouched())
					((Activity)getContext()).finish();
				else
					if (intro.getGame().isTouched()){
						jogo.Play();
						atual = Tela.JOGO;
					}
					else
						if (intro.getCredits().isTouched()){
							atual = Tela.CREDITS;
						}
				break;
	
			case JOGO:
				jogo.onTouchEvent(event);
				break;
		}
		return true;
	}

	public void Update()
	{
		switch(atual)
		{
			case CREDITS :
				credits.Update();
				break;
				
			case INTRO:
				intro.Update();
				break;
	
			case JOGO:
				if (!jogo.isPlaying){
					jogo.Clear();
					atual = Tela.INTRO;
				}
				else
					jogo.Update(getWidth(), getHeight());
				break;
		}
	}

	public void onDraw(Canvas spriteBatch)
	{
		switch(atual)
		{
			case CREDITS :
				credits.Draw(spriteBatch);
				break;
				
			case INTRO:
				intro.Draw(spriteBatch);
				break;
	
			case JOGO:
				jogo.Draw(spriteBatch);
				break;
		}
	}
}